import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gag.annotation.disclaimer.WrittenWhile;

public class ARNFCServer { 
    public static final int SERVERPORT = 1337;
 
    private ServerSocket serverSocket;
    
    private Map<String, String> sharedData;
    
    private List<Socket> clients;
    
    public static void main(String[] args){
    	new ARNFCServer();
    }
    
    public ARNFCServer(){
    	sharedData = new HashMap<String, String>();
    	clients = new ArrayList<Socket>();
    	Thread serverThread = new Thread(new ServerThread());
        serverThread.start();
    }
 
    public class ServerThread implements Runnable {
    	
    	@WrittenWhile("Being pretty tired")
        public void run() {
            try {
                serverSocket = new ServerSocket(SERVERPORT);
                while (true) {   
                	System.out.println("Listening on port " + SERVERPORT);
                	final Socket client = serverSocket.accept();
                    System.out.println("Connected to IP " + client.getInetAddress());
                    clients.add(client);
                	
                    new Thread(){
                    	public void run(){
                    		try {	
                    			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    			
	                            String line = null;
	                            while ((line = in.readLine()) != null) {
	                                System.out.println("ARNFCServer: Received " + line + " from " + client.getInetAddress());
//	                                if(line.split(":").length == 1){
//	                                	if(sharedData.containsKey(line)){
//	                                		getSharedData(line);
//	                                	}
//	                                	else{
////	                                		sendMessageToClient("none");
//	                                		updateValuesToClients("none");
//	                                	}
//	                                }
//	                                else{
		                                String firstWord = line.substring(0, line.indexOf(":"));
		                                String theRest = line.substring(line.indexOf(":") + 1);
		                                
		                                System.out.println("Setting " + firstWord + " to " + theRest);
		                                setSharedData(firstWord, theRest);
//	                                }
	                            }
	                        } catch (Exception e) {
//		                            System.err.println("ARNFCServer: Oops. Connection interrupted. Please reconnect your phone.");
//		                            e.printStackTrace();
	                        	clients.remove(client);
	                        }
                    	}
                    	
//                    	private void getSharedData(String key){
////                    		System.out.println("Sending " + sharedData.get(key) + " to client.");
//                    		sendMessageToClient(client, key + ":" + sharedData.get(key));
////                    		updateValuesToClients(key + ":" + sharedData.get(key));
//                    	}
                    	
                    	private void setSharedData(String key, String value){
                    		System.out.println("Setting " + key + " to " + value);
                    		sharedData.put(key, value);
                    		updateValueToClients(key + ":" + value);
                    	}
                    	
                    	
                    }.start();
                }
            } catch (Exception e) {
                System.err.println("ARNFCServer: Error");
                e.printStackTrace();
            }
        }
    }
    
    private void sendMessageToClient(Socket client, String message){
		System.out.println("Sending " + message + " to client.");
		PrintWriter out;
		try {
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client
			        .getOutputStream())), true);
			out.write(message + "\n");
        	out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    private void updateValueToClients(String message){
    	System.out.print("Updating client values...");
    	for(Socket client : clients){
    		sendMessageToClient(client, message);
    	}
    	System.out.println(" Done.");
    }
}
